# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp.osv import fields, osv
from openerp.tools.translate import _


import datetime
from datetime import timedelta
from requests.packages.charade import _description_of
from tzlocal.darwin import get_localzone

class crea8s_exer1_class(osv.osv):
    _name = "crea8s.exer1.class"
    _description = "exer1.class-crea8s_t1"
    _columns = {
        'name': fields.char('Name', size=50),
        'date': fields.datetime('Date...+Time'),
        'date_stop': fields.datetime('Date Stop...+Time'),
        'name1': fields.char('Name1-Password', size=50),
        'date1': fields.datetime('Date1...+Time'),
        'name2': fields.char('Name2', size=50),
        'date2': fields.datetime('Date2...+Time'),
        'name3': fields.char('Name3', size=50),
        'date3': fields.datetime('Date3...+Time'),
        'chk_yes': fields.boolean('Yes'),
        'chk_no': fields.boolean('No'),

        'partner_ref': fields.many2one('res.partner', 'Partner'),
        'exer_tri_n1_detail': fields.one2many('exer1.detail', 'exer1_detail_id', 'Details'),
        'note': fields.text('Note', size=100),
        'exer1_one': fields.many2one('exer1.detail', 'exer1_one aaa'),
        
        
        'curr_obj_id': fields.char('curr_obj_id!!!', size=50),
        'exer1_prod1': fields.many2many('product.product', 'cons_exer1_prod1', 'id1', 'id2', 'exer1_prod1..'),

        #related !!!!
        'credit_limit': fields.related('partner_ref', 'credit_limit', type='float', relation='res.partner', string='credit limit..', store=True),
        #
        'number1': fields.float('Number 1', digits=(3,1)),
    }
    strFormatTime = '%Y-%m-%d %H-%M-%S %Z'
    
    
    def B2_2_TinhDienTichHinhChuNhata(self, cr, uid, ids, context={}):
        objPractice = self.pool.get('crea8s.training1.demo.class')
        # objPractice.B2_2_TinhDienTichHinhChuNhata(cr, uid, ids, context)
        self.processORM(cr, uid, ids);
        return True
    
    
    def processORM(self, cr, uid, ids):
        
        print 'processORM...'
#         self.search(cr, uid, [('name','ilike','%name%')])
        arrIDs = self.search(cr, uid, [('name', 'like', 'ame ')])
        print '+ search-char: (arrIDs) = ' + str(arrIDs)
        
        arrIDs = self.search(cr, uid, [('date', '<=', '2014-06-02')])  # can NOT for datetime ???
        print '+ search-datetime: (arrIDs) = ' + str(arrIDs)
        
        arrIDs = self.search(cr, uid, [('chk_yes', '=', True)])
        print '+ search-boolean: (arrIDs) = ' + str(arrIDs)
        
        # create
        strNewID = self.create(cr, uid, {'name': 'crea8s_exer1_class 01',
                              # 'date': datetime.datetime.now(get_localzone()).strftime(self.strFormatTime),                                
                              })
        print '+ create-char: (strNewID)=' + str(strNewID)
        
        # read
        arrRead = self.read(cr, uid, ids, ['name', 'date'])  # ???        
        print '+ read-char: (arrRead)=' + str(arrRead)
        arrRead = self.read(cr, uid, [3, 5], ['name', 'date'])  # ???        
        print '+ read-char: (arrRead[3,5])=' + str(arrRead)
        
        arrRead = self.read_group(cr, uid, [], ['name', 'note'], ['name', 'note'])  # ???        
        print '+ read_group-char: (arrRead  GROUP)=' + str(arrRead)
        
        objTemp = self.write(cr, uid, [7], {'name': 'name 07'})  # ok
        print '+ write-objTemp: ' + str(objTemp) 
        
#         objTemp = self.copy(cr, uid, [57])  # ok; ERROR: may be turned out: "unhashable type: 'list'"
#         print '+ copy-objTemp: ' + str(objTemp)
         
        objTemp = self.unlink(cr, uid, [47])  # ok
        print '+ unlink-objTemp: ' + str(objTemp) 
        
        objTemp = self.browse(cr, uid, [3, 5, 6])
        print '+browse: ...'
        for item in objTemp:
            print '++ item.name: ' + str(item.name)
            if len(item.exer_tri_n1_detail) > 0:
                for detail in item.exer_tri_n1_detail:
                    print '+++ detail: ' + str(detail.name) 
        
        return True
    
    def get_credit(self, cr, uid, ids, partner_ref, note):
        flCredite = 0
        if partner_ref:
            objPractice = self.pool.get('res.partner')
            arrTmp = objPractice.read(cr, uid, [partner_ref], ['name', 'credit_limit'])
            print 'get_credit'
            print '+ arrTmp' + str(arrTmp)
            if len(arrTmp) == 1:
                flCredite = arrTmp[0]['credit_limit']       
        else:    
            print 'get_credit: partner_ref = 0000' 
        
        return  {'value': {'note': flCredite}}
    
#     def create(self, cr, uid, arrVals, context=None):
#         
#         # change name; case 1: browse partner
#         objPractice = self.pool.get('res.partner')
#         print 'create... crea8s_exer1_class.py'
# #         arrTmp = objPractice.browse(cr, uid, [arrVals['partner_ref']])  => array
#         if 'partner_ref' in arrVals: # neu co chon partner_ref
#             arrTmp = objPractice.browse(cr, uid, arrVals['partner_ref'])  # => item: getattr(arrTmp, 'name'); arrTmp['name']; arrTmp.name
#             print 'arrTmp' + str(arrTmp)
# #             if arrTmp:
# #                 print 'arrTmp===' + str(arrTmp.name)
# #             else:
# #                 print 'arrTmp==NULLaaaa'
#             
# #             if arrTmp:  # null, ""
# #                 print 'arrTmp[0].partner_ref.name' + str(arrTmp.name)       
# #                 arrVals['name'] = str(arrVals['name']) + '; ' + str(arrTmp.name) + '; ' + str(arrVals['date'])  # str(str(arrTmp[0].partner_ref.name)) +  
#             
#         
#         # change name; case 2: browse self ; only on WRITE/UPDATE methods
#         
#         # change note
#         if 'note' in arrVals:
#             arrVals['note'] = str(arrVals['note']) + '.create'
#         else:
#             arrVals['note'] = str('aaa') + '.create'
#                 
#         print 'create... END'
#         return super(crea8s_exer1_class, self).create(cr, uid, arrVals, context)
    
    def write(self, cr, uid, ids, arrVals, context=None):
        
        print 'write-arrVals: ' + str(arrVals)

        # change name; case 2: browse self ; only on WRITE/UPDATE methods   ////
        arrTmp = self.browse(cr, uid, ids)
        for item in arrTmp:
            strPartnetName = ""
            strDate = ""
            
            if 'partner_ref' in arrVals:
                objPractice = self.pool.get('res.partner')
        #         arrTmp = objPractice.browse(cr, uid, [arrVals['partner_ref']])  => array
                arrTmp2 = objPractice.browse(cr, uid, arrVals['partner_ref'])  # => item: getattr(arrTmp, 'name'); arrTmp['name']; arrTmp.name
                if arrTmp:  # null, ""
                    strPartnetName + str(arrTmp2.name)
                else:
                    strPartnetName = 'partner_ref-NOTfound: ' + arrVals['partner_ref']        
            else:
                strPartnetName = str(item.partner_ref.name) # error ..
                
                
            if 'date' in arrVals:
                strDate = arrVals['date']
            else:
                strDate = str(item.date)
                
            if 'name' in arrVals:
                arrVals['name'] = arrVals['name'] + strPartnetName + '; ' + strDate
            else:
                arrVals['name'] = str(item.name) + strPartnetName + '; ' + strDate
                
                
        # decode/ encode
        # n''
        # change note
#         if 'note' in arrVals:
#             arrVals['note'] = str(arrVals['note'] ) + '.write_update'
#         else:
#             arrVals['note'] = 'notChanged.write_update'
        arrTmp = self.browse(cr, uid, ids)
        for item in arrTmp:            
            if 'note' in arrVals:
                arrVals['note'] = arrVals['note'] + '.write_update(byBrowsing)'
            else:
                arrVals['note'] = str(item.note) + 'notChanged.write_update(byBrowsing)' 
        
        
        return super(crea8s_exer1_class, self).write(cr, uid, ids, arrVals, context)
    
    def btn_close(self, cr, uid, ids, context={}):
        print 'btn_close...'
        return {'type': 'ir.actions.act_window_close'}
     
    # 
class exer1_detai(osv.osv):
    _name = 'exer1.detail'
    _description = 'exer1_detail...'
    _rec_name = 'code'  # search field
    _columns = {
         'exer1_detail_id': fields.many2one('crea8s.exer1.class', 'exer1 detail id'),
         'code': fields.char('Code', size=56),
         'name': fields.char('Name', size=128),
         'date': fields.date('Date'),
         'total': fields.float('Total', digits=(3, 1)),
                
    }
    

crea8s_exer1_class()


